import config from '@/config/config.js';
class SocketSelf {
	constructor(uid,roomType,_uni) {
		this.uid = uid
		this.roomType = roomType
		this.url = `${config.wsBaseUrl}studyRoom/${uid}/${roomType}`
		this.socketTask = uni.connectSocket({
		    url: this.url, 
		    complete: (res)=> {
				// this.initSocketTask()
				console.log(res)
			}
		});
		return this
	}
	
	getSocketTask(){
		return this.socketTask
	}
	sockOnMessage(){
		this.socketTask.onMessage((data)=>{
			// 接收服务端消息data
			console.log(data)
		})
	}
	sockSend(param,_uni){
		console.log("发送数据：" + JSON.stringify(param))
		if(_uni){
			this._uni = _uni
		}
		// 发送数据
		this.socketTask.send({
			// 消息数据
			data:JSON.stringify(param),
			// 成功回调
			success:res=>{
				console.log(res)
			},
			// 失败回调
			fail:err=>{
				console.log(err)
			}
		})
	}
	sockClose(){
		// 连接关闭
		this.socketTask.close({
			// 关闭连接，1000表示正常关闭
			code:1000,
			// 成功回调
			success:res=>{
				console.log(res)
			},
			// 失败回调
			fail:err=>{
				console.log(err)
			}
		})
	}
	sockOnOpen(){
		// 监听连接打开
		this.socketTask.onOpen(res=>{
			// res服务端返回数据
			console.log(this.url + " - 连接打开")
			clearInterval(this.timeer)
		})
	}
	set_uni(_uni){
		this._uni = _uni
	}
	initSocketTask(_uni){
		// 接收服务端消息data
		if(_uni){
			this._uni = _uni
		}
		console.log("初始化socket连接")
		this.sockOnOpen()
		// 接收消息监听
		this.socketTask.onMessage((data)=>{
			console.log(data)
			let res = JSON.parse(data.data)
			switch(this.roomType){
				case 1:
				this._uni.selfKY = res.data
				break;
				case 2:
				this._uni.selfKY = res.data
				break;
				case 3:
				this._uni.selfKY = res.data
				break;
				case 4:
				this._uni.selfKY = res.data
				break;
			}
		})
		// 连接关闭回调
		this.socketTask.onClose(res=>{
			// 连接关闭回调
			console.log(this.url + " - 连接关闭")
		})
		// 连接发生错误
		this.socketTask.onError(err=>{
			console.log(this.url + " - 连接错误")
			console.log(err)
			this.timeer = setInterval(()=>{
				console.log("重试连接")
				let sock = new SocketChat(this.uid)
				this.socketTask = sock
				this.initSocketTask()
			},1000)
		})
	}
}

export {
	SocketSelf
}